import { Config, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import * as request from 'request';
import * as _ from 'lodash';
import * as crypto from 'crypto';
const moment = require('moment');

/**
 * http请求封装
 */
@Provide()
export class TaoBaoRequestService extends BaseService {
  @Config('module.task')
  taskConfig;

  /**
   * post
   */
  //获取所有的淘宝店铺订单信息
  getTbList(data = {}, start, end, sessionKey) {
    data['app_key'] = '34490344';
    data['format'] = 'json';
    data['sign_method'] = 'md5';
    data['v'] = '2.0';
    data['method'] = 'taobao.open.trades.sold.get';
    data['session'] = sessionKey;
    // data['session'] = 'taobao.open.trades.sold.get';

    data['fields'] =
      'tid,type,status,payment,orders,rx_audit_status,buyer_nick';
    data['timestamp'] = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    data['start_created'] = start;
    data['end_created'] = end;

    // 示例用法
    const secret = 'aa20b37d7dc37c3846c0f14669c9f5c4';
    const signMethod = 'md5';
    const signature = this.signTopRequest(data, secret, signMethod);
    data['sign'] = signature;
    return new Promise((resolve, reject) => {
      var option = {
        url: 'https://eco.taobao.com/router/rest',
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'content-type': 'application/json',
        },
        form: data,
      };
      request(option, function (error, response, body) {
        resolve(body.open_trades_sold_get_response);

        // if (!error && response.statusCode == 200) {
        //   const { code, data } = body;
        //   if (code === 1) {
        //     resolve(data);
        //   } else {
        //     reject(body);
        //   }
        // } else {
        //   reject(error); // 返回错误信息
        // }
      });
    });
  }

  getTbTest(data = {}, sessionKey, orderId) {
    data['app_key'] = '34490344';
    data['format'] = 'json';
    data['sign_method'] = 'md5';
    data['v'] = '2.0';
    data['method'] = 'taobao.trade.fullinfo.get';
    data['session'] = sessionKey;
    // data['session'] = 'taobao.open.trades.sold.get';

    data['fields'] = 'tid,type,status,payment,orders,promotion_details';
    data['tid'] = orderId;
    data['timestamp'] = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    // 示例用法
    const secret = 'aa20b37d7dc37c3846c0f14669c9f5c4';
    const signMethod = 'md5';
    const signature = this.signTopRequest(data, secret, signMethod);
    data['sign'] = signature;
    return new Promise((resolve, reject) => {
      var option = {
        url: 'https://eco.taobao.com/router/rest',
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'content-type': 'application/json',
        },
        form: data,
      };
      request(option, function (error, response, body) {
        resolve(body);

        // if (!error && response.statusCode == 200) {
        //   const { code, data } = body;
        //   if (code === 1) {
        //     resolve(data);
        //   } else {
        //     reject(body);
        //   }
        // } else {
        //   reject(error); // 返回错误信息
        // }
      });
    });
  }

  //签名操作
  signTopRequest(params, secret, signMethod) {
    // delete params['sign'];
    // 第一步：检查参数是否已经排序
    const keys = Object.keys(params).sort();

    // 第二步：把所有参数名和参数值串在一起
    let query = '';
    if (signMethod === 'md5') {
      // 签名的摘要算法，可选值为：hmac，md5，hmac-sha256
      query += secret;
    }
    for (const key of keys) {
      const value = params[key];
      if (key && value) {
        query += key + value;
      }
    }

    // 第三步：使用MD5/HMAC加密
    let bytes;
    if (signMethod === 'hmac') {
      bytes = this.encryptHMAC(query, secret);
    } else {
      query += secret;
      bytes = this.encryptMD5(query);
    }

    // 第四步：把二进制转化为大写的十六进制
    return this.byteToHex(bytes);
  }

  encryptHMAC(data, secret) {
    const hmac = crypto.createHmac('md5', secret);
    hmac.update(data);
    return hmac.digest();
  }

  encryptMD5(data) {
    const md5 = crypto.createHash('md5');
    md5.update(data);
    return md5.digest();
  }

  byteToHex(bytes) {
    return Buffer.from(bytes).toString('hex').toUpperCase();
  }
}
